<template>
    <view class="cert-wrap" :data-theme="globPrimary">
        <u-navbar title="证书详情"></u-navbar>

        <template v-if="!loading">
            <view class="cert-area" id="pagePoster">
                <scroll-view scroll-y class="cert-scroll-view">
                    <view class="title" :data-enode="certData.cert_info.title">
                        {{ certData.cert_info.title }}
                    </view>
                    <view class="content">
                        <u-parse :html="certData.cert_info.content"></u-parse>
                    </view>
                    <view class="course" v-if="!$u.test.empty(certData.course_list)">
                        <view
                            class="item"
                            v-for="(item, index) in certData.course_list"
                            :key="index"
                        >
                            {{ item.title }}
                        </view>
                    </view>
                </scroll-view>
                <image
                    class="chapter"
                    :src="receiveRenderBase64(certData.cert_info.official_seal_base64)"
                    :class="certData.cert_info.official_seal_place"
                    v-if="certData.cert_info.official_seal_place != 'none'"
                ></image>
                <image
                    class="bg"
                    :src="receiveRenderBase64(certData.cert_info.background_base64)"
                    data-etype="image"
                ></image>
            </view>
            <!-- #ifdef H5 -->
            <edu-button type="primary" @click="canvasImage.generateImage">保存证书</edu-button>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS -->
            <edu-button type="primary" @click="capture">保存证书</edu-button>
            <!-- #endif -->
        </template>
    </view>
</template>

<script>
import { pathToBase64, base64ToPath } from '@/utils/imageTools.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            certData: null,
            posterUrl: '', // 生成画布的图片
            viewHeight: 0,
            viewTop: 0,
            loading: true,
        }
    },
    onLoad(option) {
        this.getCertData(option.id)
    },
    computed: {
        ...mapGetters({
            globPrimary: 'designSetting/getGlobTheme',
            globPrimaryColor: 'designSetting/getGlobThemeColor',
        }),
    },
    methods: {
        // #ifdef H5
        // h5获取生成的base64 图片路径
        receiveRenderData(val) {
            this.posterUrl = val.replace(/[\r\n]/g, '') // 去除base64位中的空格
            let link = document.createElement('a')
            let url = this.posterUrl
            // 这里是将url转成blob地址，
            fetch(url)
                .then((res) => res.blob())
                .then((blob) => {
                    // 将链接地址字符内容转变成blob地址
                    link.href = URL.createObjectURL(blob)
                    link.download = ''
                    document.body.appendChild(link)
                    link.click()
                })
            this._hideLoading()
        },
        // #endif
        // #ifdef APP-PLUS
        /* app截图保存到本地 */
        capture() {
            let _this = this
            _this._showLoading('下载中，请稍后')
            let pages = getCurrentPages() //获取当前页面信息
            let page = pages[pages.length - 1]
            let bitmap = null
            let currentWebview = page.$getAppWebview()
            bitmap = new plus.nativeObj.Bitmap('pagePoster')
            let height = _this.viewHeight
            if (this.$u.os() == 'android') {
                height = _this.viewHeight + _this.viewTop
            }
            currentWebview.draw(
                bitmap,
                function () {
                    let rand = Math.floor(Math.random() * 10000)
                    let saveUrl = '_doc/' + rand + 'a.jpg'
                    bitmap.save(
                        saveUrl,
                        {},
                        function (i) {
                            _this.saveImage(i.target)
                            bitmap.clear() // 清除Bitmap对象
                        },
                        function (e) {
                            bitmap.clear() // 清除Bitmap对象
                            _this._hideLoading()
                            console.log('保存图片失败', e)
                        }
                    )
                },
                function (e) {
                    console.log('截屏绘制图片失败', e)
                    _this._hideLoading()
                },
                {
                    check: true,
                    clip: {
                        top: _this.viewTop + 'px',
                        left: '0px',
                        width: '100%',
                        height: height + 'px',
                    },
                }
            )
        },
        // 查询各节点的信息
        selecterQueryInfo() {
            let query = uni.createSelectorQuery()
            query
                .select('#pagePoster')
                .boundingClientRect((data) => {
                    this.viewHeight = data.height
                    this.viewTop = data.top
                })
                .exec()
        },
        // #endif
        getCertData(id) {
            this.loading = true
            this._showLoading('努力加载中~')
            this.$edu.api
                .getUserCertDetail({
                    id,
                })
                .then((res) => {
                    const { data } = res
                    this.certData = data
                    this.loading = false
                    setTimeout(() => {
                        // #ifdef APP-PLUS
                        this.selecterQueryInfo()
                        // #endif
                        this._hideLoading()
                    }, 500)
                })
        },
        // 保存图片到手机相册
        saveImage(filePath) {
            uni.saveImageToPhotosAlbum({
                filePath, // 需要临时文件路径，base64无法保存
                success: () => {
                    this._showToast('保存图片成功')
                    this._hideLoading()
                },
                fail: () => {
                    this._showToast('保存失败，请重试')
                    this._hideLoading()
                },
            })
        },
        // 获取生成的base64 图片路径
        receiveRenderBase64(val) {
            return val.replace(/[\r\n]/g, '') // 去除base64位中的空格
        },
        // 显示loading
        _showLoading(str) {
            uni.showLoading({
                title: str,
                mask: true,
            })
        },
        // 隐藏loading
        _hideLoading() {
            uni.hideLoading()
        },
        // 报错alert
        _errAlert(content) {
            uni.showModal({
                title: '提示',
                content: content,
            })
        },
        // 提示弹窗
        _showToast(msg) {
            uni.showToast({
                title: msg,
                icon: 'none',
            })
        },
    },
}
</script>

<script lang="renderjs" module="canvasImage">
// #ifdef H5
import html2canvas from "html2canvas";
export default {
    methods: {
        // 生成图片需要调用的方法
        generateImage(e, ownerFun) {
            ownerFun.callMethod("_showLoading", "下载中，请稍后"); // 生成图片的 loading 提示
            setTimeout(() => {
                const dom = document.getElementById("pagePoster"); // 需要生成图片内容的 dom 节点
                html2canvas(dom, {
                    width: dom.clientWidth, //dom 原始宽度
                    height: dom.clientHeight,
                    scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
                    scrollX: 0,
                    useCORS: true, //支持跨域
                    // scale: 2, // 设置生成图片的像素比例，默认是1，如果生成的图片模糊的话可以开启该配置项
                })
                    .then((canvas) => {
                        // 生成成功
                        // html2canvas 生成成功的图片链接需要转成 base64位的url
                        ownerFun.callMethod(
                            "receiveRenderData",
                            canvas.toDataURL("image/png")
                        );
                    })
                    .catch((err) => {
                        // 生成失败 弹出提示弹窗
                        ownerFun.callMethod(
                            "_errAlert",
                            `【生成图片失败，请重试】${err}`
                        );
                    });
            }, 300);
        },
    },
};
// #endif
</script>

<style lang="scss" scoped>
.cert-wrap {
    .cert-area {
        height: 1060rpx;
        padding: 100rpx 98rpx;
        position: relative;
        .cert-scroll-view {
            height: 100%;
            position: relative;
            z-index: 9;
        }
        .title {
            font-size: 32rpx;
            font-weight: bold;
            color: $edu-main-color;
            line-height: 40rpx;
            letter-spacing: 2rpx;
            text-align: center;
        }
        .content {
            margin-top: 30rpx;
        }
        .course {
            margin-top: 30rpx;
            border: 1px solid #b7bac1;
            border-top: 0;
            .item {
                padding: 16rpx 30rpx;
                color: $edu-main-color;
                font-size: 16rpx;
                text-align: center;
                border-top: 1px solid #b7bac1;
            }
        }
        .chapter {
            position: absolute;
            z-index: 10;
            width: 132rpx;
            height: 132rpx;
            &.right-top {
                right: 30rpx;
                top: 107rpx;
            }
            &.right-bottom {
                right: 30rpx;
                bottom: 67rpx;
            }
        }
        .bg {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 8;
            width: 100%;
            height: 100%;
        }
    }
    .edu-btn {
        margin: 45rpx 35rpx 0;
    }
}
</style>
